#include "EventLoop.h"
#include "Channel.h"
#include "Logger.h"

#include <sys/epoll.h>

/// @brief Channel关注的事件状态
const int Channel::kNoneEvent = 0;
const int Channel::kReadEvent = EPOLLIN | EPOLLPRI;
const int Channel::kWriteEvent = EPOLLOUT;

/**
 * @brief Channel的构造和析构
 *
 * @param loop
 * @param fd
 */
Channel::Channel(EventLoop *loop, int fd)
    : loop_(loop), fd_(fd), events_(0), revents_(0), index_(-1), tied_(false)
{
}
Channel::~Channel()
{
}

void Channel::tie(const std::shared_ptr<void> &obj)
{
    tie_ = obj;
    tied_ = true;
}
/**
 * @brief 通过父组件Eventloop更新poller关注的事件
 *
 */
void Channel::update()
{
    loop_->updateChannel(this);
}
void Channel::remove()
{
    loop_->removeChannel(this);
}

void Channel::handlEvent(Timestamp receiveTime)
{
    if (tied_)
    {
        std::shared_ptr<void> guard = tie_.lock();
        if (guard)
        {
            handleEventWithGuard(receiveTime);
        }
    }
    else
    {
        handleEventWithGuard(receiveTime);
    }
}

// 根据poller返回的就绪事件，调用对应回调函数处理
void Channel::handleEventWithGuard(Timestamp receiveTime)
{
    LOG_INFO("channel fd=%d handleEvent revents:%d\n", fd_, revents_);
    if ((revents_ & EPOLLHUP) && !(revents_ & EPOLLIN))
    {
        if (closeCallback_)
        {
            closeCallback_();
        }
    }
    if (revents_ & EPOLLERR)
    {
        if (errorCallback_)
        {
            errorCallback_();
        }
    }
    if (revents_ & (EPOLLIN | EPOLLPRI))
    {
        if (readCallback_)
        {
            readCallback_(receiveTime);
        }
    }
    if (revents_ & EPOLLOUT)
    {
        if (writeCallback_)
        {
            writeCallback_();
        }
    }
}